package com.xncoding.valid.service;

import com.xncoding.valid.dto.Person;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.MapBindingResult;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Set;

@Service
public class PersonService {
    // inject javaee validator object
    @Resource
    private Validator validator ;
    // inject spring validator object
    @Resource
    private org.springframework.validation.Validator valid ;

    public void validator(Person person) {
        Set<ConstraintViolation<Person>> res = validator.validate(person) ;
        res.forEach(cv -> {
            System.out.println(cv.getMessage()) ;
        });
        System.out.println("----------------------") ;
        BindingResult errors = new MapBindingResult(new HashMap<String, Object>(), "person") ;
        valid.validate(person, errors) ;
        if (errors.hasErrors()) {
            errors.getAllErrors().forEach(oe -> {
                System.out.println(oe.getDefaultMessage()) ;
            });
        }
    }

}
